//
//  TTCommitOrderViewController.m
//  TaoTuo
//
//  Created by 周晨晔 on 2019/9/23.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTCommitOrderViewController.h"
#import "TTCommitOrderHeaderView.h"
#import "TTAddressModel.h"
#import "TTMyAddressViewController.h"
#import "TTShopCartDiamondViewCell.h"
#import "TTShopCartCommodityViewCell.h"
#import "TTShopCartMultyViewCell.h"
#import "TTShopCartSubDetailModel.h"
#import "YBImageBrowser.h"
#import "TTDiamondDetailViewController.h"
#import "TTShopCartMultyModel.h"
#import "TTGoodsDetailViewController.h"
#import "TTDiamondPopListView.h"
#import <TYAlertView.h>
#import <UIView+TYAlertView.h>
#import "TTDiamondsRecommendModel.h"
#import "TTCommonViewCell.h"
#import "TTCellLabelModel.h"
#import "TTCellLabelArrowModel.h"
#import "TTCommondDataModel.h"
#import "TTExtractAddressViewController.h"
#import "TTCommitSuccessViewController.h"
#import "TTCommitFailViewController.h"

#import "TTCouponViewController.h"
#import "TTCouponModel.h"

#import "TTPayOrderViewController.h"
#import "TTInlayRuleModel.h"

#import "TTFactoryAddressViewController.h"

#define cellType @"cellTypeKey"
#define cellData @"cellDataKey"
#define titleKey @"titleKey"
#define canSelectKey @"canSelectKey"
#define isInsetProductKey @"isInsetProductKey" // 可镶嵌产品的区域

static NSString *luoshiCellID = @"shop_commit_luoshi_cell_id";        // 裸石
static NSString *commodityCellID = @"shop_commit_commodity_cell_id";  // 商品
static NSString *multyCellID = @"shop_commit_multy_cell_id";      // 一个cell里面有多个商品的
static NSString *infoCellID = @"info_cell_id";      // 信息

typedef enum : NSUInteger {
    CellTypeWithMulty,  //多个
    CellTypeWithSingle,  //单个
    CellTypeWithInfo    // 信息
} CellType;

@interface TTCommitOrderViewController ()<UITableViewDelegate, UITableViewDataSource, TTCommitOrderHeaderViewDelegate, TTShopCartMultyViewCellDelegate, TTShopCartDiamondViewCellDelegate>
{
    TTDiamondPopListView *_popView;
    NSInteger _index;   // 已匹配的镶嵌产品的顺序
    TTCellLabelArrowModel *couponInfoModel; // 优惠券
    TTCellLabelModel *couponsMoneyModel; // 优惠金额
    TTCellLabelModel *insetMoneyModel;  // 镶嵌费
    TTCellLabelModel *zsMoneyModel;  // 证书费
    CGFloat totalMoney;             // 总金额
    CGFloat couponMoney;    // 优惠券金额
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger originalShopCount;    // 原来商品个数

@property (nonatomic, strong) TTCommitOrderHeaderView *headerView;
@property (nonatomic, strong) NSMutableArray *shopArray;
@property (nonatomic, strong) NSMutableArray *canInsetArray;    // 能镶嵌的商品
@property (nonatomic, strong) NSMutableArray *diamondArray;     // 商品中包含的裸石
@property (nonatomic, strong) TTShopCartSubDetailModel *clickModel;    // 点击的model
@property (nonatomic, strong) TTDiamondsRecommendModel *diamondModel;
@property (nonatomic, strong) NSMutableArray *matchedArray; // 已匹配的列表

@property (nonatomic, strong) UILabel *totalMoneyLabel;     // 订单总金额

@property (nonatomic, strong) NSMutableArray *couponArray;  // 优惠券

@property (nonatomic, strong) TTCouponModel *selectCPModel;   // 选中的优惠券
@property (nonatomic, copy) NSString *couponGoodsBarCode;   // 优惠券的GoodsBarCode
@property (nonatomic, assign) NSInteger totalCoupon;    // 请求到的优惠券个数
@property (nonatomic, strong) NSArray *currentShopCanInsetDiamondArray; // 当前选中的商品能镶嵌的裸石
@property (nonatomic, strong) NSMutableArray *indexPathArray;   // 存放已经做过动画的indexPath
@property (nonatomic, strong) NSMutableArray *inlayRuleArray;   // 镶嵌费规则数组
///是否需要提示镶嵌
@property (nonatomic, assign) BOOL needHintInlay;
///是否只有裸石
@property (nonatomic, assign) BOOL isOnlyLuoshi;
/// 提交订单按钮
@property (nonatomic, strong) UIButton *commitBtn;

@end

@implementation TTCommitOrderViewController

- (instancetype)initWithShopArray:(NSArray<TTShopCartSubDetailModel *> *)shopArray diamondModel:(nullable TTDiamondsRecommendModel *)diamondModel
{
    self = [super init];
    if (self) {
        
        self.diamondModel = diamondModel;
        self.originalShopCount = shopArray.count;
        self.shopArray = [[NSMutableArray alloc] initWithArray:shopArray copyItems:YES];
        
        self.isOnlyLuoshi = YES;
        for (TTShopCartSubDetailModel *model in self.shopArray) {
            // 都设为未选中状态
            model.Number = model.Number > 0 ? model.Number : 1;
            model.isSelect = NO;
            if (model.GoodsType == 1) {
                if (model.DiaSize.length == 0) {
                    model.DiaSize = [NSString stringWithFormat:@"%.0f", model.InsertSize.intValue / 100.0];
                }
                [self.diamondArray addObject:model];    // 找出裸石
            } else {
                // 空托或成品，重新计算高度
                model.h = [self calculateContentHeightWithModel:model];
                self.isOnlyLuoshi = NO;
            }
            
        }
        
        [self.dataArray addObject:@{cellType : @(CellTypeWithSingle), cellData : self.shopArray, titleKey : @"商品列表"}];
        
        NSArray *arr = [[NSArray alloc] initWithArray:shopArray copyItems:YES];
        for (TTShopCartSubDetailModel *model in arr) {
            model.isSelect = NO;
            if (model.GoodsType == 1 || model.FinishedProduct || model.InsertSize.intValue < 3) {
                continue;
            }
            model.Number = model.Number > 0 ? model.Number : 1;
            model.h = [self calculateContentHeightWithModel:model];
            // 镶嵌费初始值
            model.insetMoney = @"0";//[self getInsetChargeWithInsetSize:model.InsertSize];
            // 能镶嵌的，遍历一下是为了处理定制的可能会有多件商品，把它们分开来处理
            for (int i = 0; i < model.Number; i++) {
                TTShopCartSubDetailModel *modelCopy = model.copy;
                modelCopy.Number = 1;           //分开之后把商品数量设置为1
                [self.canInsetArray addObject:modelCopy];
            }
        }
        
    }
    return self;
}
//防止多次推出页面发出多次通知
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self addNotifyEvent];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (_popView) {
        _popView.superview.hidden = NO;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"提交订单";
    //镶嵌费规则
    [self getIgetInlayPriceRule];
    // 地址
    [self getAddressData];
    // 优惠券
    [self getCouponsInfo];

    
}

///添加通知
- (void)addNotifyEvent
{
    // 点击戒托的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chooseShopNotify:) name:@"chooseShop_key" object:nil];
    
    // 点击关闭弹出的视图
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closePopViewNotify:) name:@"closePopView_key" object:nil];

    // 选择完毕的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chooseAllFinishedNotify:) name:@"chooseAllFinishedNotify_key" object:nil];
    
    // 移除已匹配的产品的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteMatchedProductNotify:) name:@"deleteMatchedProductNotify_key" object:nil];
    
    // header 设置完毕刷新
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshHeaderViewNotify) name:@"refreshHeaderViewNotify_key" object:nil];
}

- (void)refreshHeaderViewNotify
{
    [self.headerView layoutIfNeeded];
    
    [self.tableView reloadData];
}

- (void)chooseShopNotify:(NSNotification *)notify
{
    self.needHintInlay = NO;
    self.clickModel = notify.object;
    if (self.clickModel.isSelect) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.InsertSize == %@.InsertSize", self.clickModel];
        NSArray *resultArray = [self.diamondArray filteredArrayUsingPredicate:predicate];
        NSMutableArray *arr = [NSMutableArray array];
        for (TTShopCartSubDetailModel *m in resultArray) {
            if (!m.luoshiSelect) {
                [arr addObject:m];
            }
        }
        if (arr.count > 0) {
//            self.currentShopCanInsetDiamondArray = [[NSArray alloc] initWithArray:arr copyItems:YES];
            self.currentShopCanInsetDiamondArray = arr;
            TTDiamondPopListView *popView = [TTDiamondPopListView popListViewWithDataArray:self.currentShopCanInsetDiamondArray];
            [popView showInView:nil animationDuration:0.5];
            self->_popView = popView;
        } else {
            self.currentShopCanInsetDiamondArray = nil;
            // 请求裸石数据
            [self getDiamondData];
        }
        
    } else {
        // 不选中，移除掉匹配的产品
        TTShopCartMultyModel *shouldRemoveModel;
        for (TTShopCartMultyModel *multyModel in self.matchedArray) {
            TTShopCartSubDetailModel *dm = multyModel.array.firstObject;
            if (self.clickModel.GoodsBarCode == dm.GoodsBarCode) {
                shouldRemoveModel = multyModel;
                break;
            }
        }
        
        NSNotification *notify = [NSNotification notificationWithName:@"deleteMatchedProductNotify_key" object:shouldRemoveModel];
        [self removeMatchedShopsWithNotify:notify];
        
        
    }
}

- (void)closePopViewNotify:(NSNotification *)notify
{
    self.clickModel.isSelect = NO;
    [self.tableView reloadSection:0 withRowAnimation:UITableViewRowAnimationFade];
}

// 计算镶嵌费
- (NSString *)calculateInlayMoneyWithStoneSize:(NSString *)insertSize
{
    NSInteger money = 0;
    CGFloat size = insertSize.floatValue * 100;
    for (TTInlayRuleModel *model in self.inlayRuleArray) {
        if (size >= model.InsertSizeMin && size < model.InsertSizeMax) {
            money = model.InlayValuationPriceType == 0 ? model.InlayPrice : (NSInteger)(size * model.UnitPrice);
            break;
        }
    }
    return [NSString stringWithFormat:@"%ld", money];
}

// 选择完毕，展示出来
- (void)chooseAllFinishedNotify:(NSNotification *)notify
{
    // 第一个元素是裸石数据TTShopCartSubDetailModel，第二个是质检数据TTQualityCheckModel
    NSArray *notifyArr = notify.object;
    TTShopCartSubDetailModel *luoshiModel = notifyArr.firstObject;
    luoshiModel.luoshiSelect = YES;
    // 计算镶嵌费
    self.clickModel.insetMoney = [self calculateInlayMoneyWithStoneSize:luoshiModel.DiaSize];
    // 为了设置镶嵌费所以copy一下
    TTShopCartSubDetailModel *modelCopy = self.clickModel.copy;
    modelCopy.h = [self calculateContentHeightWithModel:modelCopy]; // 计算高度
    modelCopy.insetMoney = nil;
    NSArray *array = @[modelCopy, luoshiModel];
    TTShopCartMultyModel *model = [TTShopCartMultyModel setArray:array title:self.clickModel.GoodsTitle qualityCheckModel:notifyArr.lastObject];
    for (TTShopCartSubDetailModel *dm in array) {
        model.cellHeight += dm.h;
    }
    _index++;
    NSString *title = _index == 1 ? @"已匹配的镶嵌产品" : @"";
    [self.dataArray insertObject:@{cellType : @(CellTypeWithMulty), cellData : @[model], canSelectKey : @(NO), titleKey : title} atIndex:_index];
    
    // 添加到已匹配的数组中
    [self.matchedArray addObject:model];
    
    // 添加到商品数据中
    BOOL has = NO;
    for (TTShopCartSubDetailModel *m in self.diamondArray) {
        if ([luoshiModel.GoodsBarCode isEqualToString:m.GoodsBarCode]) {
            has = YES;
            break;
        }
    }
    if (!has) {
        [self.shopArray addObject:luoshiModel];
    }
    
    // 计算费用
    [self calculatePrice];
    
    [self.tableView reloadData];
}

// 移除已匹配的产品的通知
- (void)deleteMatchedProductNotify:(NSNotification *)notify
{
    @weakify(self)
    LLSystemAlertView *alertView = [LLSystemAlertView alertViewWithTitle:@"提示" message:@"确定移除该镶嵌组合吗？" cancelTitle:@"取消" cancelBlock:nil confirmTitle:@"确定" confirmBlock:^BOOL{
        // 刷新页面
        @strongify(self)
        [self removeMatchedShopsWithNotify:notify];
        return YES;
    }];
    [alertView showInWindowWithBackgoundTapDismissEnable:YES];
}

- (void)removeMatchedShopsWithNotify:(NSNotification *)notify
{
    TTShopCartMultyModel *model = notify.object;
    
    for (NSDictionary *dic in self.dataArray) {
        id obj = [dic[cellData] firstObject];
        if ([obj isKindOfClass:[TTShopCartMultyModel class]] && obj == model) {
            [self.dataArray removeObject:dic];
            break;
        }
    }
    [self.matchedArray removeObject:model];
    // 找出与移除的产品相匹配的产品，设置不选中
    TTShopCartSubDetailModel *dModel = model.array.firstObject;
    for (TTShopCartSubDetailModel *subDetailModel in self.canInsetArray) {
        if ([subDetailModel.GoodsBarCode isEqualToString:dModel.GoodsBarCode]) {
            subDetailModel.isSelect = NO;
            dModel.isSelect = NO;
            break;
        }
    }
    
    _index--;
    if (_index == 1) {
        // 重新设置区头标题
        NSDictionary *dic = self.dataArray[1];
        NSMutableDictionary *mDic = [NSMutableDictionary dictionaryWithDictionary:dic];
        [mDic setObject:@"已匹配的镶嵌产品" forKey:titleKey];
        [self.dataArray replaceObjectAtIndex:1 withObject:mDic];
    }
    
    // 删除商品中的裸石(如果不在原商品中，就删除掉)
    TTShopCartSubDetailModel *luoshiModel = model.array.lastObject;
    luoshiModel.luoshiSelect = NO;
    BOOL has = NO;
    for (TTShopCartSubDetailModel *m in self.diamondArray) {
        if ([luoshiModel.GoodsBarCode isEqualToString:m.GoodsBarCode]) {
            has = YES;
            break;
        }
    }
    if (!has) {
        [self.shopArray removeObject:luoshiModel];
    }
    
    // 计算费用
    [self calculatePrice];
    
    [self.tableView reloadData];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSDictionary *dic = self.dataArray[section];
    return [dic[cellData] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.dataArray[indexPath.section];
    if ([dic[cellType] integerValue] == CellTypeWithSingle) {
        TTShopCartSubDetailModel *detailModel = dic[cellData][indexPath.row];
        if (detailModel.GoodsType == 1) {
            // 裸石
            TTShopCartDiamondViewCell *cell = [tableView dequeueReusableCellWithIdentifier:luoshiCellID];
            [cell setDetailModel:detailModel hasShadow:YES canSelect:[dic[canSelectKey] boolValue] isFromCommitOrder:YES];
            cell.delegate = self;
            return cell;
        } else {
            TTShopCartCommodityViewCell *cell = [tableView dequeueReusableCellWithIdentifier:commodityCellID];
            [cell setDetailModel:detailModel hasShadow:YES canSelect:[dic[canSelectKey] boolValue] isFromCommitOrder:YES];
            return cell;
        }
    } else if ([dic[cellType] integerValue] == CellTypeWithMulty){
        TTShopCartMultyModel *multyModel = dic[cellData][indexPath.row];
        // 包含多个
        TTShopCartMultyViewCell *cell = [tableView dequeueReusableCellWithIdentifier:multyCellID];
        [cell setMultyModel:multyModel canSelect:[dic[canSelectKey] boolValue] sectionViewCanSelect:NO isFromCommitOrder:YES];
        cell.delegate = self;
        return cell;
    } else {
        TTCommonViewCell *cell = [tableView dequeueReusableCellWithIdentifier:infoCellID];
        cell.model = dic[cellData][indexPath.row];
        return cell;
    }
    
}

// cell即将出现做动画
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.dataArray[indexPath.section];
    if ([dic[cellType] integerValue] == CellTypeWithMulty){
        if ([self.indexPathArray containsObject:indexPath]) {
            return;
        }
        [self.indexPathArray addObject:indexPath];
        cell.transform = CGAffineTransformMakeScale(0.2, 0.2);
        [UIView animateWithDuration:0.6 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.3 options:UIViewAnimationOptionCurveLinear animations:^{
            cell.transform = CGAffineTransformMakeScale(1, 1);
            cell.alpha = 1;
        } completion:^(BOOL finished) {
            
        }];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.dataArray[indexPath.section];
    if ([dic[cellType] integerValue] == CellTypeWithInfo) {
        TTCellModel *model = dic[cellData][indexPath.row];
        if ([model isKindOfClass:[TTCellLabelArrowModel class]]) {
            TTCellLabelArrowModel *am = (TTCellLabelArrowModel *)model;
            if ([self respondsToSelector:am.selector]) {
                IMP imp = [self methodForSelector:am.selector];
                void (*func)(id, SEL) = (void *)imp;
                func(self, am.selector);
            }
        }
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.dataArray[indexPath.section];
    if ([dic[cellType] integerValue] == CellTypeWithSingle) {
        TTShopCartSubDetailModel *detailModel = dic[cellData][indexPath.row];
        return detailModel.h;
    } else if ([dic[cellType] integerValue] == CellTypeWithMulty) {
        TTShopCartMultyModel *model = dic[cellData][indexPath.row];
        return model.cellHeight + 40 + 10; // 加上区头高度
    } else {
        return 44;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    NSDictionary *dic = self.dataArray[section];
    NSString *title = dic[titleKey];
    if (title.length == 0) {
        return 0;
    }
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSDictionary *dic = self.dataArray[section];
    NSString *title = dic[titleKey];
    if (title.length == 0) {
        return [UIView new];
    }
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 40)];
    view.backgroundColor = [UIColor whiteColor];
    UILabel *label = [UILabel labelWithTitle:title color:UIColorHex(333333) fontSize:15];
    label.frame = CGRectMake(10, 0, self.view.width - 20, view.height);
    [view addSubview:label];
    return view;
}

#pragma mark - TTShopCartDiamondViewCellDelegate, TTShopCartCommodityViewCellDelegate, TTShopCartMultyViewCellDelegate
- (void)clickLookCertificateWithModel:(TTShopCartSubDetailModel *)model
{
    // 查看证书
    [TTLoginSingle lookCertificateWithUrlString:model.CertPic];
    
}


#pragma mark - TTCommitOrderHeaderViewDelegate
// 选择地址
- (void)clickChooseAddressBtnWithHeaderView:(TTCommitOrderHeaderView *)headerView
{
    @weakify(self)
    if (headerView.receiveType == ReceiveTypeWithMail) {
        // 邮寄
        TTMyAddressViewController *addressVC = [[TTMyAddressViewController alloc] initWithSelectBlock:^(TTAddressModel * _Nonnull model) {
            @strongify(self)
//            [self.headerView setModel:model isMail:YES];
            [self.headerView setModel:model receiveType:ReceiveTypeWithMail];
        }];
        [self.navigationController pushViewController:addressVC animated:YES];
        
    } else if (headerView.receiveType == ReceiveTypeWithSelfTake) {
        // 自提
        TTExtractAddressViewController *extractVC = [[TTExtractAddressViewController alloc] initWithSelectBlock:^(TTAddressModel * _Nonnull model) {
            @strongify(self)
//            [self.headerView setModel:model isMail:NO];
            [self.headerView setModel:model receiveType:ReceiveTypeWithSelfTake];
        }];
        extractVC.addressModel = headerView.model;
        [self.navigationController pushViewController:extractVC animated:YES];
        
    } else if (headerView.receiveType == ReceiveTypeWithSendFactory) {
        TTFactoryAddressViewController *factoryVC = [[TTFactoryAddressViewController alloc] initWithSelectBlock:^(TTAddressModel * _Nonnull model) {
            @strongify(self)
            [self.headerView setModel:model receiveType:ReceiveTypeWithSendFactory];
        }];
        [self.navigationController pushViewController:factoryVC animated:YES];
    }
    
//    if (headerView.isMail) {
//        // 邮寄
//        @weakify(self)
//        TTMyAddressViewController *addressVC = [[TTMyAddressViewController alloc] initWithSelectBlock:^(TTAddressModel * _Nonnull model) {
//            @strongify(self)
//            [self.headerView setModel:model isMail:YES];
//        }];
//        [self.navigationController pushViewController:addressVC animated:YES];
//    } else {
//        // 自提
//        @weakify(self)
//        TTExtractAddressViewController *extractVC = [[TTExtractAddressViewController alloc] initWithSelectBlock:^(TTAddressModel * _Nonnull model) {
//            @strongify(self)
//            [self.headerView setModel:model isMail:NO];
//        }];
//        extractVC.addressModel = headerView.model;
//        [self.navigationController pushViewController:extractVC animated:YES];
//    }
    
    
}

// 裸石数据
- (void)getDiamondData
{
    // 找出带过来的裸石的goodsBarCode
    NSMutableArray *diamondGoodsBarCodeArray = [NSMutableArray array];
    for (TTShopCartSubDetailModel *model in self.currentShopCanInsetDiamondArray) {
        [diamondGoodsBarCodeArray addObject:model.GoodsBarCode];
    }
    NSArray *sizeArray = [self.clickModel.InsertSizeRang componentsSeparatedByString:@"_"];
    
    NSDictionary *dic = @{
        @"param.shape" : self.clickModel.MStoneMosaicShape,
        @"param.goodsBarCodeList" : diamondGoodsBarCodeArray.count == 0 ? @[@""] : diamondGoodsBarCodeArray,
        @"param.insizeRangeMin" : sizeArray.firstObject,
        @"param.insizeRangeMax" : sizeArray.lastObject,
    };
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:recommendedDiamond_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        NSMutableArray *totalDiamondArray = [NSMutableArray array];
        // 添加当前商品中能镶嵌的裸石列表
        for (TTShopCartSubDetailModel *model in self.currentShopCanInsetDiamondArray) {
            model.ProductText = @"";
            [totalDiamondArray addObject:model];
        }
        NSMutableArray *arr = [NSMutableArray array];
        for (NSDictionary *dic in responseObject) {
            TTDiamondModel *model = [TTDiamondModel modelWithJSON:dic];
            [arr addObject:[TTCommondDataModel diamondModelToShopCartSubDetailModelWithModel:model]];
        }
        // 过滤
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT(SELF.GoodsBarCode in %@.GoodsBarCode)", self.currentShopCanInsetDiamondArray];
        NSArray *canShowArray = [arr filteredArrayUsingPredicate:predicate];
        //再过滤
        NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"NOT(SELF.GoodsBarCode in %@.GoodsBarCode)", self.shopArray];
        NSArray *canShowArray2 = [canShowArray filteredArrayUsingPredicate:predicate2];
        
        [totalDiamondArray addObjectsFromArray:canShowArray2];
        
        if (totalDiamondArray.count == 0) {
            [self.view makeToast:@"没有可镶嵌的裸石" duration:1 position:CSToastPositionCenter];
            self.clickModel.isSelect = NO;
            [self.tableView reloadData];
            return;
        }
        TTDiamondPopListView *popView = [TTDiamondPopListView popListViewWithDataArray:totalDiamondArray];
        [popView showInView:nil animationDuration:0.5];
        self->_popView = popView;
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        
        
    } showLoadingInView:self.view];
}


// 点击需镶嵌按钮
- (void)clickInsetButton:(UIButton *)insetBtn headerView:(TTCommitOrderHeaderView *)headerView
{
    if (!insetBtn.selected) {
        if (self.canInsetArray.count == 0) {
            [self.view makeToast:@"没有可镶嵌的空托" duration:1 position:CSToastPositionCenter];
            return;
        }
        insetBtn.selected = !insetBtn.selected;
        //        TTShopCartMultyModel *model = [TTShopCartMultyModel setArray:self.canInsetArray title:@"选择镶嵌产品" hintImageName:@"hintgantanhao" hintInfo:@"暂不支持镶口10分及其以下的戒托" hintInfoColor:UIColorHex(FF1F1F)];
        TTShopCartMultyModel *model = [TTShopCartMultyModel setArray:self.canInsetArray title:@"选择镶嵌产品"];
        for (TTShopCartSubDetailModel *dm in self.canInsetArray) {
            model.cellHeight += dm.h;
        }
        [self.dataArray insertObject:@{cellType : @(CellTypeWithMulty), cellData : @[model], canSelectKey : @(YES)} atIndex:0];
        
        [self.tableView reloadData];
        
        self.needHintInlay = YES;
        
    } else {
        @weakify(self)
        self.needHintInlay = NO;
        LLSystemAlertView *alertView = [LLSystemAlertView alertViewWithTitle:@"温馨提示" message:@"取消镶嵌服务后刚刚的镶嵌配置都将失效" cancelTitle:@"取消" cancelBlock:nil confirmTitle:@"确定" confirmBlock:^BOOL{
            // 刷新页面
            @strongify(self)
            insetBtn.selected = !insetBtn.selected;
            // 1. 设置状态为未选中
            NSDictionary *dic = self.dataArray.firstObject;
            TTShopCartMultyModel *model = [dic[cellData] firstObject];
            for (TTShopCartSubDetailModel *dm in model.array) {
                dm.isSelect = NO;
                dm.luoshiSelect = NO;
            }
            // 2. 倒序删除已匹配选中的
            NSArray *reverseArray = [[self.dataArray reverseObjectEnumerator] allObjects];
            for (NSDictionary *subDic in reverseArray) {
                if ([subDic[cellType] integerValue] == CellTypeWithMulty) {
                    [self.dataArray removeObject:subDic];
                }
            }
            // 3. 删除商品列表中匹配到的产品
            if (self.shopArray.count > self.originalShopCount) {
                // 多出来的个数
                NSInteger count = self.shopArray.count - self.originalShopCount;
                // 删除
                [self.shopArray removeObjectsInRange:NSMakeRange(self.originalShopCount, count)];
            }
            self->_index = 0;
            [self.matchedArray removeAllObjects];
            
            // 计算费用
            [self calculatePrice];
            
            [self.tableView reloadData];
            
            return YES;
        }];
        [alertView showInWindowWithBackgoundTapDismissEnable:YES];

    }
    
    
}

// 最终要提交的商品
- (NSMutableArray *)getFinalCommitDataArray
{
    // 存放最终要提交的商品
    NSMutableArray *goodsListArray = [NSMutableArray array];
    // 1. 已匹配到的产品
    for (TTShopCartMultyModel *multyModel in self.matchedArray) {
        TTShopCartSubDetailModel *ktModel = multyModel.array.firstObject;
        TTShopCartSubDetailModel *luoshiModel = multyModel.array.lastObject;
        ktModel.InlayNumber = @1;
        luoshiModel.InlayNumber = @1;
        ktModel.DiaSize = luoshiModel.DiaSize;
        // 交换barCode
        NSString *barCode = ktModel.GoodsBarCode;
        if (ktModel.GoodsType != 2) {
            ktModel.GoodsInlayRelateBarCode = luoshiModel.GoodsBarCode;
        }
        luoshiModel.GoodsInlayRelateBarCode = barCode;
        
        if (ktModel.GoodsType != 2) {
            ktModel.GoodsInlayCertTypeCode = @(multyModel.qualityCheckModel.CertType);
        }
        luoshiModel.GoodsInlayCertTypeCode = @(multyModel.qualityCheckModel.CertType);
        
        if (ktModel.GoodsType != 2) {
            ktModel.GoodsInlayCertType = multyModel.qualityCheckModel.CertTypeName;
        }
        luoshiModel.GoodsInlayCertType = multyModel.qualityCheckModel.CertTypeName;
        
        BOOL canAdd = YES;
        int i = 1;
        for (TTShopCartSubDetailModel *dm in goodsListArray) {
            if ([dm.GoodsBarCode isEqualToString:ktModel.GoodsBarCode]) {
                i += ktModel.InlayNumber.intValue;
                canAdd = NO;
                dm.DiaSize = [NSString stringWithFormat:@"%@,%@", dm.DiaSize, ktModel.DiaSize];
            }
            if (dm.GoodsType == 2) {
                //共有几个镶嵌了
                dm.InlayNumber = @(i);
            }
        }
        
        if (canAdd) {
            [goodsListArray addObject:ktModel];
        }
        [goodsListArray addObject:luoshiModel];
    }
    
    //选出来 goodsListArray 里面的定制商品
    NSPredicate *customPredicate = [NSPredicate predicateWithFormat:@"GoodsType == 2"];
    NSArray *customGoodsArray = [goodsListArray filteredArrayUsingPredicate:customPredicate];
    for (TTShopCartSubDetailModel *dm in customGoodsArray) {
        for (TTShopCartSubDetailModel *sdm in self.shopArray) {
            if ([sdm.GoodsBarCode isEqualToString:dm.GoodsBarCode]) {
                //定制的商品的数量
                dm.Number = sdm.Number;
            }
        }
    }

    
    // 2. 找到未匹配的商品
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT(GoodsBarCode in %@.GoodsBarCode)", goodsListArray];
    NSArray *otherGoodsArray = [self.shopArray filteredArrayUsingPredicate:predicate];
    // 2.1 把未匹配的商品也添加到 goodsListArray 中
    [goodsListArray addObjectsFromArray:otherGoodsArray];
    
    
    return goodsListArray;
}

// 提交订单
- (void)commitOrderAction
{
    // 2. 验证收货地址是否填写
    if (self.headerView.tapBtn.currentTitle.length > 0) {
        [self.view makeToast:self.headerView.tapBtn.currentTitle duration:1 position:CSToastPositionCenter];
        return;
    }
    
    if (self.headerView.receiveType == ReceiveTypeWithSendFactory) {
        if (self.headerView.khmTF.text.length == 0) {
            NSString *str = [NSString stringWithFormat:@"请输入%@", self.headerView.khmTF.placeholder];
            [self.view makeToast:str duration:1 position:CSToastPositionCenter];
            return;
        }
        
        if (self.headerView.contactTF.text.length == 0) {
            NSString *str = [NSString stringWithFormat:@"请输入%@", self.headerView.contactTF.placeholder];
            [self.view makeToast:str duration:1 position:CSToastPositionCenter];
            return;
        }
        
        if (self.headerView.factoryTF.text.length == 0) {
            NSString *str = [NSString stringWithFormat:@"请输入%@", self.headerView.factoryTF.placeholder];
            [self.view makeToast:str duration:1 position:CSToastPositionCenter];
            return;
        }
    } else {
//        // 1. 验证手机号是否填写
//        if (self.headerView.phoneTF.text.length == 0) {
//            NSString *str = [NSString stringWithFormat:@"请输入%@", self.headerView.phoneTF.placeholder];
//            [self.view makeToast:str duration:1 position:CSToastPositionCenter];
//            return;
//        }
//        // 保存输入下单人的手机号
//        [USER_DEFAULT setObject:self.headerView.phoneTF.text forKey:@"order_phone_key"];
        if (self.headerView.phoneTF.text.length > 0) {
            // 保存输入下单人的手机号
            [USER_DEFAULT setObject:self.headerView.phoneTF.text forKey:@"order_phone_key"];
        }
        
    }
    
    if (self.needHintInlay) {
        @weakify(self)
        LLSystemAlertView *alertView = [LLSystemAlertView alertViewWithTitle:@"确定提交订单" message:@"您勾选了镶嵌服务，但是还没有选择需要镶嵌的空托，确认需要提交吗？" cancelTitle:@"取消" cancelBlock:nil confirmTitle:@"确定" confirmBlock:^BOOL{
            @strongify(self)
            [self confirmCommitShopOrder];
            
            return YES;
        }];
        [alertView showInWindowWithBackgoundTapDismissEnable:YES];
    } else {
        [self confirmCommitShopOrder];
    }
    
    
    
}

- (void)confirmCommitShopOrder
{
    self.commitBtn.enabled = NO;
    
    // 存放最终要提交的商品
    NSMutableArray *goodsListArray = [self getFinalCommitDataArray];
    // 获取优惠券的goodsBarCode
    if (self.selectCPModel == nil) {
        [self commitOrderWithGoodsListArray:goodsListArray couponGoodsBarCode:nil];
    } else {
        @weakify(self)
        [self getCouponGoodsBarCodeWithGoodsListArray:goodsListArray success:^(NSString *couponGoodsBarCode) {
            @strongify(self)
            [self commitOrderWithGoodsListArray:goodsListArray couponGoodsBarCode:couponGoodsBarCode];
        }];
    }
}

- (void)commitOrderWithGoodsListArray:(NSMutableArray *)goodsListArray couponGoodsBarCode:(NSString *)couponGoodsBarCode
{
    NSMutableArray *goodsList = [NSMutableArray array];
    for (TTShopCartSubDetailModel *dm in goodsListArray) {
        // 把描述转成json字符串
        NSData *describeData = [NSJSONSerialization dataWithJSONObject:dm.GoodsDescribe options:NSJSONWritingFragmentsAllowed error:nil];
        NSString *describeStr = [[NSString alloc] initWithData:describeData encoding:NSUTF8StringEncoding];
        NSDictionary *dic = @{
            @"GoodsBarCode": dm.GoodsBarCode,
            @"GoodsType": @(dm.GoodsType),
            @"GoodsTitle": dm.GoodsTitle,
            @"GoodsImage": dm.GoodsImage,
            @"GoodsDescribe": describeStr,
            @"GoodsPrice": dm.GoodsPrice,
            @"GoodsCertTypeCode": dm.CertType,
            @"GoodsCertType": dm.Cert,
            @"GoodsCertNo": dm.CertNo,
            @"GoodsCertPic": dm.CertPic,
            @"GoodsCertQueryCode": dm.QueryCode,
            @"GoodsNumber": @(dm.Number),
            @"InlayNumber": dm.InlayNumber ? : @0,
            @"GoodsInlayRelateBarCode": dm.GoodsInlayRelateBarCode ? : @"",
            @"GoodsInlayCertTypeCode": dm.GoodsInlayCertTypeCode ? : @"",
            @"GoodsInlayCertType": dm.GoodsInlayCertType ? : @"",
            @"FactoryLabel": dm.FactoryLabel ? : @"",
            @"GoodsGrade": dm.ProductGrade,
            @"GoodsGradeName" : dm.ProductGradeName,
            @"GoldColor": dm.CustomizedGoldColor,
            @"InsertDiaSize" : dm.DiaSize,
            @"ClarityCharacteristics": dm.ClarityCharacteristics,
            @"GoodsMadeCircle" : dm.Cycle,
            @"GoodsLocation" : dm.LocationName,
            @"PriceDiffRang" : dm.PriceDiffRang,
            @"StockTypeName" : dm.StockTypeName
        };
        [goodsList addObject:dic];
    }
    
    NSNumber *num = @(self.headerView.receiveType);
    TTAddressModel *adModel;
    if (self.headerView.receiveType == ReceiveTypeWithSendFactory) {
        adModel = self.headerView.factoryModel;
    } else {
        adModel = self.headerView.model;
    }
    NSString *phone = [self.headerView.phoneTF.text removeBlank].length > 0 ? [self.headerView.phoneTF.text removeBlank] : @"-";
    NSMutableDictionary *dic = @{
        //        @"RelationId": 0,
        @"WholesalerName": [TTLoginSingle sharedSingle].loginModel.RealName,
        @"ReciveType": num,                            // 1.邮寄 2.自提，3.送长
        @"BatchSource": @1,                           // 订单来源 1
        //        @"PlusShopCustomerName": "string",           // 空 @“”
        //        @"PlusShopOrderNo": "string",                // 空 @“”
        @"ReceiverName": adModel.ReceiverName, // 收货人姓名
        @"ReceiverMobile": adModel.ReceiverMobile,// 收货人电话
        @"ReceiverProvince": adModel.Province, // 省
        @"ReceiverCity": adModel.City,    // 市
        @"ReceiverArea": adModel.Area, // 区
        @"ReceiverAddress": adModel.Address, // 地址
        @"OrderMobile": phone,  // 填写的手机号
        @"Remark": self.headerView.remarkTF.text,  // 备注
        @"DiscountTicketId": self.selectCPModel.Id,                    // 优惠券的ID
        @"DiscountGoodsBarCode": couponGoodsBarCode ? : @"",       // 优惠券的goodsbarcode
        @"DiscountPrice": self.selectCPModel.CouponMoney ? : @"0",                     // 优惠券的金额
        @"InlayPrice": [insetMoneyModel.content substringFromIndex:1],  // 总镶嵌费
        @"CertPrice": [zsMoneyModel.content substringFromIndex:1], // 总的证书费
        @"OrderRealPayPrice": [_totalMoneyLabel.text substringFromIndex:1], // 订单总金额
        @"SalesmanAccountId": [TTLoginSingle sharedSingle].loginModel.SalesmanAccountId,
        @"SalesmanAccountName": [TTLoginSingle sharedSingle].loginModel.SalesmanAccountName,
        @"SalesmanMobile": [TTLoginSingle sharedSingle].loginModel.SalesmanMobile,
        @"GoodsList" : goodsList
    }.mutableCopy;
    
    if (self.headerView.receiveType == ReceiveTypeWithSendFactory) {
        dic[@"FactoryOpenBankName"] = self.headerView.khmTF.text;
        dic[@"ReceiverName"] = self.headerView.contactTF.text;
        dic[@"OrderMobile"] = [self.headerView.factoryTF.text removeBlank];
        dic[@"FactoryName"] = adModel.ReceiverName;
        [dic removeObjectForKey:@"Remark"];
    }
    
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postJsonWithUrlString:commitOrder_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        [[NSNotificationCenter defaultCenter] postNotificationName:@"setPageRefreshStatusNotify" object:nil];
        // 提交成功，去支付页面
        NSString *money_str = [self.totalMoneyLabel.text substringFromIndex:1];
        NSString *address_str = [NSString stringWithFormat:@"%@%@%@%@", self.headerView.model.Province, self.headerView.model.City, self.headerView.model.Area, self.headerView.model.Address];
        NSString *nameAndphone = [NSString stringWithFormat:@"%@    %@", self.headerView.model.ReceiverName, self.headerView.model.ReceiverMobile];
        
        TTPayOrderViewController *vc = [[TTPayOrderViewController alloc] initWithOrderNum:responseObject totalMoney:money_str address:address_str nameAndphone:nameAndphone];
        [self.navigationController pushViewController:vc animated:YES];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        @strongify(self)
        // 提交失败
        TTCommitFailViewController *vc = [[TTCommitFailViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
    } showLoadingInView:self.view];
}

// 获取地址
- (void)getAddressData
{
    co_launch(^{
        
        TTAddressModel *model1 = await([self getNormalAddress]);
        TTAddressModel *model2 = await([self getFactoryAddress]);
        
        self.headerView = [TTCommitOrderHeaderView headerViewWithAddress:model1 isNeedInset:!self.isOnlyLuoshi];
        self.headerView.factoryModel = model2;
        [self.headerView setModel:model1 receiveType:ReceiveTypeWithMail];
        self.headerView.delegate = self;
        self.headerView.phoneTF.text = [USER_DEFAULT objectForKey:@"order_phone_key"];
        self.tableView.tableHeaderView = self.headerView;
        
    });
}

- (COPromise *)getNormalAddress
{
    COPromise *promise = [COPromise promise];
    
    NSDictionary *dic = @{
            @"param.pageIndex" : @(1),
            @"param.pageSize" : @(10)
        };
        
        [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:getAddressList_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSArray *arr = responseObject;
            
            TTAddressModel *model = [TTAddressModel modelWithJSON:arr.firstObject];
            
            [promise fulfill:model];
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
            
            [promise fulfill:nil];
            
        } showLoadingInView:nil];
    
    return promise;
    
}

/// 获取工厂地址
- (COPromise *)getFactoryAddress
{
    COPromise *promise = [COPromise promise];
    
    NSDictionary *dic = @{
        @"param.pageIndex" : @(1),
        @"param.pageSize" : @10
    };
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:getFactoryAddress_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSArray *arr = responseObject;
        
        TTAddressModel *model = [TTAddressModel modelWithJSON:arr.firstObject];
        
        [promise fulfill:model];
        
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        [promise fulfill:nil];
    } showLoadingInView:self.tableView];
    
    return promise;
    
}


///获取镶嵌费规则
- (void)getIgetInlayPriceRule
{
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postUrlString:getInlayPriceRule parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        [self.inlayRuleArray removeAllObjects];
        for (NSDictionary *dic in responseObject) {
            TTInlayRuleModel *model = [TTInlayRuleModel modelWithJSON:dic];
            [self.inlayRuleArray addObject:model];
        }
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
}

// 获取优惠券信息
- (void)getCouponsInfo
{
    [self calculatePrice];  // 计算费用
    NSMutableArray *nameArray = [NSMutableArray array];
    NSMutableArray *styleLibraryIdArray = [NSMutableArray array];
    for (TTShopCartSubDetailModel *model in self.shopArray) {
        [nameArray addObject:model.CategoryName];
        if (model.GoodsType != 1) {
            [styleLibraryIdArray addObject:model.StyleLibraryId];
        }
    }
    NSDictionary *dic = @{
        @"TotalPrice" : @(totalMoney),
        @"PageIndex" : @1,
        @"PageSize" : @100,
        @"CouponState" : @0,
        @"CategoryName" : nameArray,
        @"StyleLibraryId" : styleLibraryIdArray
    };
    
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postJsonWithUrlString:getCouponList_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        NSArray *arr = responseObject;
        self.couponArray = [NSMutableArray array];
        for (NSDictionary *subDic in arr) {
            TTCouponModel *cpModel = [TTCouponModel modelWithJSON:subDic];
            [self.couponArray addObject:cpModel];
        }
        self.totalCoupon = arr.count;   // 总优惠券的个数
        // 1.添加剩余的信息
        [self addCellInfoData];
        // 2. footerview
        [self setupFooterViewWithTotalPrice:self->totalMoney];
        // 3.添加底部view
        [self setupBottomView];
        
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:nil];
}


// 计算费用
- (void)calculatePrice
{
    // 1. 计算镶嵌费
    CGFloat insetMoney = 0.0;
    for (TTShopCartSubDetailModel *dm in self.canInsetArray) {
        if (dm.isSelect) {
            insetMoney += dm.insetMoney.floatValue;
        }
    }
    insetMoneyModel.content = [NSString stringWithFormat:@"￥%.0f", insetMoney];
    
    // 2. 计算证书费
    CGFloat zsMoney = 0.0;
    for (TTShopCartMultyModel *mm in self.matchedArray) {
        zsMoney += mm.qualityCheckModel.Price.floatValue;
    }
    zsMoneyModel.content = [NSString stringWithFormat:@"￥%.0f", zsMoney];
    
    // 3. 计算总金额
    totalMoney = 0.0;
    for (TTShopCartSubDetailModel *model in self.shopArray) {
        int count = model.Number > 0 ? model.Number : 1;
        totalMoney += model.GoodsPrice.floatValue * count;
    }
    totalMoney += (insetMoney + zsMoney) - couponMoney;
    self.totalMoneyLabel.text = [NSString stringWithFormat:@"￥%.0f", totalMoney];
}

// 获取优惠券的goodsBarCode
- (void)getCouponGoodsBarCodeWithGoodsListArray:(NSMutableArray *)goodsListArray success:(void(^)(NSString *couponGoodsBarCode))success
{
    // 存放最终要提交的商品
    NSMutableArray *arr = [NSMutableArray array];
    for (TTShopCartSubDetailModel *model in goodsListArray) {
        NSDictionary *dic = @{
            @"GoodsBarCode" : model.GoodsBarCode,
            @"StyleCategoryName" : model.CategoryName,
            @"Price" : model.GoodsPrice
        };
        [arr addObject:dic];
    }
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:arr forKey:@"GoodsBarCode"];
    [dic setObject:self.selectCPModel.Id forKey:@"CouponId"];
    [dic setObject:self.selectCPModel.CouponMoney forKey:@"CouponPrice"];
    [dic setObject:@(self.selectCPModel.Type) forKey:@"Type"];
    [dic setObject:@(self.selectCPModel.UseRange) forKey:@"UseRange"];
    [dic setObject:self.selectCPModel.StyleLibraryId forKey:@"StyleLibraryId"];
    [dic setObject:self.selectCPModel.StyleLibraryCategory forKey:@"StyleLibraryCategory"];
    [[LLNetworkManagerTool sharedManager] postJsonWithUrlString:getCouponGoodsBarCode_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject[@"GoodsBarCode"]);
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
    
}

- (void)addCellInfoData
{
    NSMutableArray *array = [NSMutableArray array];
    couponInfoModel = [TTCellLabelArrowModel setModelWithTitle:@"优惠券" content:[NSString stringWithFormat:@"%ld张优惠券", self.totalCoupon] selector:@selector(gotoCouponsPage) contentColor:UIColorHex(FF1F1F)];
    [array addObject:couponInfoModel];
    
    couponsMoneyModel = [TTCellLabelModel setModelWithTitle:@"优惠金额" content:@"￥0" contentColor:UIColorHex(FF1F1F)];
    [array addObject:couponsMoneyModel];
    
    [array addObject:[TTCellLabelModel setModelWithTitle:@"配送费用" content:@"￥0" contentColor:UIColorHex(FF1F1F)]];
    
    insetMoneyModel = [TTCellLabelModel setModelWithTitle:@"镶嵌服务费" content:@"￥0" contentColor:UIColorHex(FF1F1F)];
    [array addObject:insetMoneyModel];
    
    zsMoneyModel = [TTCellLabelModel setModelWithTitle:@"证书费" content:@"￥0" contentColor:UIColorHex(FF1F1F)];
    [array addObject:zsMoneyModel];
    
    [self.dataArray addObject:@{cellType : @(CellTypeWithInfo), cellData : array}];
    
    
}

// 去优惠券页面
- (void)gotoCouponsPage
{
    TTCouponViewController *couponVC = [[TTCouponViewController alloc] initWithDataArray:self.couponArray showNotUseCoupon:YES];
    @weakify(self)
    couponVC.selectedCoupon = ^(TTCouponModel * _Nullable couponModel, UIViewController *vc) {
        @strongify(self)
        self.selectCPModel = couponModel;
        [vc.navigationController popViewControllerAnimated:YES];
        if (couponModel == nil) {
            // 不使用优惠券
            self->couponInfoModel.content = [NSString stringWithFormat:@"%ld张优惠券", self.totalCoupon];
            self->couponsMoneyModel.content = @"￥0";
            self->couponMoney = 0.0;
        } else {
            self->couponInfoModel.content = couponModel.Name;
            self->couponsMoneyModel.content = [NSString stringWithFormat:@"￥%@", couponModel.CouponMoney];
            self->couponMoney = couponModel.CouponMoney.floatValue;
        }
        // 计算价格
        [self calculatePrice];
        [self.tableView reloadData];
        
    };
    [self.navigationController pushViewController:couponVC animated:YES];
    
}



- (void)setupFooterViewWithTotalPrice:(CGFloat)totalPrice
{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 100)];
    // 1. 订单
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 10, footerView.width, 44)];
    topView.backgroundColor = [UIColor whiteColor];
    [footerView addSubview:topView];
    
    UILabel *titleLabel = [UILabel labelWithTitle:@"订单应付总金额" color:UIColorHex(333333) fontSize:15];
    [topView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.centerY.equalTo(topView);
    }];
    
    NSString *total = [NSString stringWithFormat:@"￥%.0f", totalPrice];
    _totalMoneyLabel = [UILabel labelWithTitle:total color:UIColorHex(FF1F1F) fontSize:15];
    [topView addSubview:_totalMoneyLabel];
    [_totalMoneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(topView).mas_offset(-10);
        make.centerY.equalTo(topView);
    }];
    
    // 2. 提示
    UIView *infoView = [[UIView alloc] initWithFrame:CGRectMake(0, topView.bottom + 10, footerView.width, 10)];
    infoView.backgroundColor = [UIColor whiteColor];
    [footerView addSubview:infoView];
    
    NSString *str = @"温馨提示：\n1、下单后客服会联系您进行包含工艺、镶嵌等服务的最终确认。\n2、如果对于下的订单有任何疑问，请联系您的专属导购进行确认。\n3、关于订单的最终加价系统只是预估算，最终成交价会有一定偏差。\n4、货品如无质量问题暂不支持退货";
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 5;
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:str];
    [attr addAttributes:@{NSForegroundColorAttributeName : UIColorHex(666666), NSFontAttributeName : [UIFont systemFontOfSize:12]} range:[str rangeOfString:@"温馨提示："]];
    [attr addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, str.length)];
    UILabel *infoLabel = [UILabel labelWithTitle:@"" color:UIColorHex(999999) fontSize:11];
    infoLabel.frame = CGRectMake(10, 10, footerView.width - 20, 10);
    infoLabel.numberOfLines = 0;
    infoLabel.attributedText = attr;
    [infoLabel sizeToFit];
    [infoView addSubview:infoLabel];
    
    infoView.height = infoLabel.height + 20;
    
    footerView.height = infoView.bottom;
    
    self.tableView.tableFooterView = footerView;
    
}

// 提交订单view
- (void)setupBottomView
{
    UIButton *btn = [UIButton createButtonWithTitle:@"提交订单" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:18] backgroundColor:kMainColor target:self action:@selector(commitOrderAction)];
    [btn setContentEdgeInsets:UIEdgeInsetsMake(-Tabbar_Bottom_height, 0, 0, 0)];
    [self.view addSubview:btn];
    self.commitBtn = btn;
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tableView.mas_bottom);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.mas_bottomLayoutGuideBottom);
    }];
}

// 获取镶嵌费
- (NSString *)getInsetChargeWithInsetSize:(NSString *)insetSize
{
    int size = insetSize.intValue;
    if (size >= 0 && size < 50) {
        return @"20";
    } else if (size >= 50 && size < 70) {
        return @"40";
    } else if (size >= 70 && size < 100) {
        return @"60";
    } else if (size >= 100 && size < 150) {
        return @"90";
    } else if (size >= 150 && size < 999999) {
        return @"20";
    }
    return @"20";
}

// 计算cell高度
- (CGFloat)calculateContentHeightWithModel:(TTShopCartSubDetailModel *)model
{
    CGFloat cellImageH = 65 * kScale + 40;
    NSString *content = [model.GoodsDescribe componentsJoinedByString:@"\n"];
    CGFloat contentH = [content boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 75 * kScale - 30, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12]} context:nil].size.height + 25;
    CGFloat sh = contentH + 35 + 35;
    sh = sh > cellImageH ? sh : cellImageH;
    return sh;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = kSeparatorColor;
        _tableView.tableFooterView = [UIView new];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[TTShopCartDiamondViewCell class] forCellReuseIdentifier:luoshiCellID];
        [_tableView registerClass:[TTShopCartCommodityViewCell class] forCellReuseIdentifier:commodityCellID];
        [_tableView registerClass:[TTShopCartMultyViewCell class] forCellReuseIdentifier:multyCellID];
        [_tableView registerClass:[TTCommonViewCell class] forCellReuseIdentifier:infoCellID];
        
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(self.mas_topLayoutGuideTop);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideTop).mas_offset(-45);
        }];
    }
    return _tableView;
}



- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}



- (NSMutableArray *)canInsetArray
{
    if (!_canInsetArray) {
        _canInsetArray = [NSMutableArray array];
    }
    return _canInsetArray;
}

- (NSMutableArray *)diamondArray
{
    if (!_diamondArray) {
        _diamondArray = [NSMutableArray array];
    }
    return _diamondArray;
}

- (NSMutableArray *)matchedArray
{
    if (!_matchedArray) {
        _matchedArray = [NSMutableArray array];
    }
    return _matchedArray;
}

- (NSMutableArray *)indexPathArray
{
    if (!_indexPathArray) {
        _indexPathArray = [NSMutableArray array];
    }
    return _indexPathArray;
}

- (NSMutableArray *)inlayRuleArray
{
    if (!_inlayRuleArray) {
        _inlayRuleArray = [NSMutableArray array];
    }
    return _inlayRuleArray;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
